<?php
defined('IN_PHPCMS') or exit('No permission resources.');
//模型缓存路径
define('CACHE_MODEL_PATH',CACHE_PATH.'caches_model'.DIRECTORY_SEPARATOR.'caches_data'.DIRECTORY_SEPARATOR);
pc_base::load_app_func('util','content');
class index {
	private $db;
	public $shoucang;
	public $articles;
	function __construct() {
//        phpinfo();
//        exit;

		$this->db = pc_base::load_model('content_model');

		$this->_userid = param::get_cookie('_userid');
		$this->_username = param::get_cookie('_username');
		$this->_groupid = param::get_cookie('_groupid');
		$favorite_model = pc_base::load_model('favorite_model');
		$_SESSION['order_sum']=0;
		$_SESSION['collect_sum']=0;
        //p($_SESSION);
		if(!empty($_SESSION['user_id']))
		{
			$user_id=$_SESSION['user_id'];
			$order_count=query_one("select count(*) count from dh_order where userid='$user_id'");
			$_SESSION['order_sum']=$order_count['count'];
			$this->shoucang=count($favorite_model->select("userid='$user_id'"));
			$_SESSION['collect_sum']=$this->shoucang;
		}

		/*$this->category = pc_base::load_model('category_model');
		$sql="select * from dh_category where catid in (118,119,120)";
		$articles = $this->category->query($sql);
		$temp=array();
		for($i=0;$i<mysql_num_rows($articles);$i++){
			$temp[$i] = mysql_fetch_assoc($articles);
		}
		$this->articles=$temp;*/
		/*$article_one=
		p($temp);*/
		//echo $this->_userid;

		//p($this->shoucang);
	}
	//首页
	public function init() {
		if(isset($_GET['siteid'])) {
			$siteid = intval($_GET['siteid']);
		} else {
			$siteid = 1;
		}
		$siteid = $GLOBALS['siteid'] = max($siteid,1);
		define('SITEID', $siteid);
		$_userid = $this->_userid;
		$_username = $this->_username;
		$_groupid = $this->_groupid;
		//SEO
		$SEO = seo($siteid);
		$sitelist  = getcache('sitelist','commons');
		$default_style = $sitelist[$siteid]['default_style'];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');
		$k= $_GET['k'];
		
			$right_ad=query_one("select setting from dh_poster where spaceid=12");
			$right_ad=$right_ad['setting'];
			$right_ad=array_slice(explode("\n", $right_ad),3,2);
			foreach ($right_ad as $k => &$v) {
                $v['linkurl']=substr($v['linkurl'],24);
				$v=explode('=>',$v);
				$v=substr($v[1], 0,-1);
				$v=str_replace("'", '', $v);
                $v=substr($v,24);
			}
		$articles=$this->articles;
		$shoucang=$this->shoucang;
		include template('content','index',$default_style);
	}
	public function gotoRegister()
	{
		//$data=$this->db->query("select * from dh_news limit 1");
		$member_model = pc_base::load_model('member_model');
		$nickname=$_POST['nickname'];
		$password=$_POST['password'];
		$email=$_POST['email'];
		$mobile=$_POST['mobile'];
		$count=$member_model->get_one("username='$nickname'");
		if(!empty($count)){
			exit(json_encode(array('isok'=>false,'msg'=>'此用户名已经存在，请直接登录','msg_code'=>'1001')));
		}

        $mobile=str_replace('-','',$mobile);
		$data=array(
			'nickname'=>$nickname,
			'username'=>$nickname,
			'email'=>$email,
			'mobile'=>$mobile,
			'password'=>$password,
			);
		$isok=$member_model->insert($data);
		if(!$isok)
		{
			exit(json_encode(array('isok'=>false,'msg'=>'注册失败请重新尝试','msg_code'=>'1002')));
		}
		$user_id=$member_model->insert_id();
		
		$_SESSION['user_id']=$user_id;
		$_SESSION['username']=$nickname;
		exit(json_encode(array('isok'=>true,'msg'=>'注册成功','msg_code'=>'1000')));
	}
	public function collect()
	{
		$user_id=$_SESSION['user_id'];
		$goods_id=$_POST['id'];
		$title=$_POST['title'];
		$url=$_POST['url'];
		$favorite_model = pc_base::load_model('favorite_model');
		$count=$favorite_model->get_one("goods_id='$goods_id' and userid='$user_id'");

		if(!empty($count)){
			exit(json_encode(array('isok'=>false,'msg'=>'此商品已经收藏，请勿重复收藏','msg_code'=>'1001')));
		}
		$goods_info=query_one("select * from dh_news where id='$goods_id'");
		$data=array(
			'goods_id'=>$goods_id,
			'title'=>$title,
			'url'=>$url,
			'adddate'=>time(),
			'userid'=>$user_id,
			'thumb'=>$goods_info['thumb']
			);
		$isok=$favorite_model->insert($data);
		if(!$isok)
		{
			exit(json_encode(array('isok'=>false,'msg'=>'收藏失败，请稍后尝试','msg_code'=>'1002')));
		}
		//header("Location:");exit;
		exit(json_encode(array('isok'=>true,'msg'=>'收藏成功','msg_code'=>'1002')));
	}
	public function delCollect()
	{
		$shoucang_id=$_POST['shoucang_id'];
		$favorite_model = pc_base::load_model('favorite_model');
		$isok=$favorite_model->delete("id='$shoucang_id'");
		if(!$isok)
		{
			exit(json_encode(array('isok'=>false,'msg'=>'删除失败，请稍后尝试','msg_code'=>'1002')));
		}
		exit(json_encode(array('isok'=>true,'msg'=>'删除成功','msg_code'=>'1002')));
	}
	public function addOrder(){

		$order_model = pc_base::load_model('order_model');

		$user_id=$_SESSION['user_id'];
		$goods_id=$_POST['id'];
		$title=$_POST['title'];
		$url=$_POST['url'];
		
		$data=array(
			'goods_id'=>$goods_id,
			'title'=>$title,
			'url'=>$url,
			'adddate'=>time(),
			'userid'=>$user_id,
			);
		$isok=$order_model->insert($data);
		$orderid=$order_model->insert_id();

		$goods=query_one("select dh_news.*,dh_news_data.coordino,dh_news_data.kuanh,dh_news_data.price from dh_news left join dh_news_data on dh_news.id=dh_news_data.id where dh_news.id=$goods_id limit 1");
		$goods['goodsid']=$goods['id'];
		$goods['orderid']=$orderid;
		unset($goods['id']);
		$order_goods_model = pc_base::load_model('order_goods_model');
		//p($order_goods_model);
		$isok=$order_goods_model->insert($goods,true);
		if(!$isok)
		{
			exit(json_encode(array('isok'=>false,'msg'=>'加入订单失败，请稍后尝试','msg_code'=>'1002')));
		}
		//header("Location:");
		exit(json_encode(array('isok'=>true,'msg'=>'加入订单成功','msg_code'=>'dd000')));
	}
	public function delOrderById(){
		
		$order_id=intval($_POST['order_id']);
		$sql="delete from dh_order where id='$order_id'";
		$res=query($sql);
		exit(json_encode(array('isok'=>true,'msg'=>'','msg_code'=>'dd000')));
	}
	public function getOrderList()
	{

		/*if(isset($_GET['siteid'])) {
			$siteid = intval($_GET['siteid']);
		} else {
			$siteid = 1;
		}
		$siteid = $GLOBALS['siteid'] = max($siteid,1);
		define('SITEID', $siteid);
		$_userid = $this->_userid;
		$_username = $this->_username;
		$_groupid = $this->_groupid;
		//SEO
		$SEO = seo($siteid);
		$sitelist  = getcache('sitelist','commons');
		$default_style = $sitelist[$siteid]['default_style'];*/
		$userid=$_SESSION['user_id'];

		$sql="select dh_order.id,dh_order_goods.goodsid,dh_order_goods.coordino,dh_order_goods.thumb,dh_order_goods.kuanh,dh_order_goods.price,SUBSTR(dh_order_goods.url,24) url,dh_order_goods.title,
(SELECT
			dh_order_qa.question_ctime
		FROM
			dh_order_qa
		WHERE
			dh_order_qa.orderid = dh_order.id
		ORDER BY question_ctime desc
		LIMIT 1
	) new_time from dh_order left join dh_order_goods on dh_order_goods.orderid=dh_order.id where dh_order.userid='$userid' order by dh_order.id desc,new_time desc,adddate desc";

		$tag='getOrderList';
		$res=query($sql);

		foreach ($res as $k => &$v) {
			if(!empty($v['id'])){
				$sql="select * from dh_order_qa where orderid=".$v['id']." order by question_ctime desc,answer_ctime desc";
				$questions=query($sql);
				foreach ($questions as $m => $n) {
					if($n['ask_type'])
					{
						if($n['question']){
							$v['user_order_question'].=''.substr($n['question_ctime'],0,-3).'&nbsp;&nbsp;'.$n['question'].'<br/>';
						}
						if($n['answer']){
							$v['admin_order_question'].=''.substr($n['answer_ctime'],0,-3).'&nbsp;&nbsp;'.$n['answer'].'<br/>';
						}
						
					}else{
						if($n['question']){
							$v['user_ask_question'].=''.substr($n['question_ctime'],0,-3).'&nbsp;&nbsp;'.$n['question'].'<br/>';
						}
						if($n['answer']){
							$v['admin_ask_question'].=''.substr($n['answer_ctime'],0,-3).'&nbsp;&nbsp;'.$n['answer'].'<br/>';
						}
					}
					
				}
			}
			
			
		}
	//p($res);
		$shoucang=$this->shoucang;
		include template('content','order_list',$default_style);
	}
	public function submitAskQuestion()
	{
		$user_id=$_SESSION['user_id'];
		$order_id=$_POST['order_id'];
		$goods_id=$_POST['goods_id'];
		$content=$_POST['info'];
		$submitType=$_POST['submitType'];
		if(empty($content))
		{
			echo "<script>alert('输入内容不能为空');history.go(-1);</script>";exit;
		}
		$order_qa_model = pc_base::load_model('order_qa_model');
		$arr=array(
			'question'=>$content,
			'question_ctime'=>date('Y-m-d H:i:s'),
			'userid'=>$user_id,
			'answer'=>'',
			'answer_ctime'=>date("Y-m-d H:i:s"),
			'orderid'=>$order_id,
			'goodsid'=>$goods_id,
			'ask_type'=>$submitType=='askType'?0:1,
			);

		$isok=$order_qa_model->insert($arr,true);
		header("Location:?m=content&c=index&a=getOrderList");exit;
		p($isok);
	}
	public function gotoLoginOut()
	{
		unset($_SESSION['user_id']);
		unset($_SESSION['username']);
		header("Location:/");
	}
	public function gotoLogin()
	{
		//$data=$this->db->query("select * from dh_news limit 1");
		$member_model = pc_base::load_model('member_model');
		$username=$_POST['username'];
		$password=$_POST['password'];
		$count=$member_model->get_one("username='$username'");
		if(empty($count)||$count['password']!=$password){
			exit(json_encode(array('isok'=>false,'msg'=>'用户名或密码错误','msg_code'=>'1001')));
		}
		$data=array(
			'lastdate'=>time(),
			'loginnum'=>$count['loginnum']+1,
			);
		$member_model->update($data,'userid='.$count['userid']);

		$_SESSION['user_id']=$count['userid'];
		$_SESSION['username']=$count['username'];
        //p($_SESSION);
		exit(json_encode(array('isok'=>true,'msg'=>'登录成功','msg_code'=>'1000')));
	}
	public function yigui() {

		$user_id=$_SESSION['user_id'];
		if(empty($user_id))
		{
			header("Location:/");exit;
			exit(json_encode(array('isok'=>false,'msg'=>'请登录后再做操作','msg_code'=>'1011')));
		}
		$con = mysql_connect("localhost","root","aide521521");
		mysql_query("set names 'utf8'");
		mysql_select_db("daohangcn", $con);
		$sql="select *,SUBSTR(dh_news.url,24) url, dh_favorite.id shoucang_id,dh_favorite.thumb fa_thumb from dh_favorite
		left join dh_news on dh_favorite.goods_id=dh_news.id left join dh_news_data on dh_news.id=dh_news_data.id where userid='$user_id' order by adddate desc ";
		$result = mysql_query($sql);
		for($i=0;$i<mysql_num_rows($result);$i++){
				$res[$i] = mysql_fetch_assoc($result);
		}	
		if(isset($_GET['siteid'])) {
			$siteid = intval($_GET['siteid']);
		} else {
			$siteid = 1;
		}
		$siteid = $GLOBALS['siteid'] = max($siteid,1);

		define('SITEID', $siteid);
		$_userid = $this->_userid;
		$_username = $this->_username;
		$_groupid = $this->_groupid;
		//SEO
		$SEO = seo($siteid);
		$sitelist  = getcache('sitelist','commons');
		$default_style = $sitelist[$siteid]['default_style'];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');
		$k= $_GET['k'];
		$tag='collect';
		$shoucang=$this->shoucang;
		include template('content','yigui',$default_style);
	}
	//导航详情
	public function daoh() {	
	
		include template('content','daoh');
	}
	
	public function yigui2()
	{
		$catid = intval($_POST['catid']);
		$ci = $_POST['ci'];
		$sear = $_POST['search'];
		$this->category = pc_base::load_model('category_model');
		$where='';
		if($catid!=''){
			$id = $this->category->get_one('catid='.$catid,'parentid');
			if($id['parentid']=='0'){
				$list = $this->category->get_one('parentid='.$catid,'catid','listorder asc');
				$cat = intval($list['catid']);
			}else{
				$cat = $catid;
			}
			$where .= 'where a.catid='.$cat;
		}
		if($catid!=''){
			if($sear!=''){
				$where .= " and a.title like '%$sear%'";
			}
		}else{
			if($sear!=''){	

				//$where .= "where a.title like '%$sear%'";
				$where .= 'where a.title like "%'.$sear.'%"';
			}
		}
		

		if($ci!=''){
			$num = '20';
			$c = $num*$ci;
			$where .= ' order by a.id desc limit '.$c.',20';
		}else{
		
			$where .= ' order by a.id desc limit 0,20';
		}
		
		$con = mysql_connect("localhost","root","aide521521");
		mysql_query("set names 'utf8'");
		mysql_select_db("daohangcn", $con);
		$sql="select a.title,a.thumb,a.catid,SUBSTR(a.url,24) url,b.price from dh_news as a left join dh_news_data as b on a.id=b.id ".$where;

		$result = mysql_query($sql);
		for($i=0;$i<mysql_num_rows($result);$i++){
				$res[$i] = mysql_fetch_assoc($result);
			}	
		$num = count($res);

		$data=array(
		'res'=>$res,
		'num'=>$num
		);
		echo json_encode($data);
	}
	public function liebiao() {	
	
		$catid = intval($_POST['catid']);
		$ci = $_POST['ci'];
		$sear = $_POST['search'];
		$paixu=$_POST['paixu'];
		
		$this->category = pc_base::load_model('category_model');
		$where='';
		if($catid!=''){
			$id = $this->category->get_one('catid='.$catid,'parentid');
			if($id['parentid']=='0'){
				$list = $this->category->get_one('parentid='.$catid,'catid','listorder asc');
				$cat = intval($list['catid']);
			}else{
				$cat = $catid;
			}
			$where .= 'where a.catid='.$cat;
		}
		if($catid!=''){
			if($sear!=''){
				$where .= " and a.title like '%$sear%'";
			}
		}else{
			if($sear!=''){	

				//$where .= "where a.title like '%$sear%'";
				$where .= 'where a.title like "%'.$sear.'%"';
			}
		}
		
		$order_by_str="";
		$order_by=array();
		if($_POST['key']=='beizhu'){
			$order_by[]="cast(description as signed) ".$_POST['val'];
		}
		if($_POST['key']=='kuanhao'){
			$order_by[]="cast(kuanh as signed) ".$_POST['val'];
		}
		if(empty($order_by)){
			$order_by[]="a.id desc";
		}
		$order_by_str.=join(',',$order_by);
		
		if($ci!=''){
			$num = '20';
			$c = $num*$ci;
			$where .= ' order by '.$order_by_str.' limit '.$c.',20';
		}else{
			$where .= ' order by '.$order_by_str.' limit 0,20';
		}
		
		$con = mysql_connect("localhost","root","aide521521");
		mysql_query("set names 'utf8'");
		mysql_select_db("daohangcn", $con);
		$sql="select a.title,a.thumb,a.catid,SUBSTR(a.url,24) url,b.price from dh_news as a left join dh_news_data as b on a.id=b.id ".$where;
//p($sql);
		$result = mysql_query($sql);
		for($i=0;$i<mysql_num_rows($result);$i++){
				$res[$i] = mysql_fetch_assoc($result);
			}	
		$num = count($res);

		$data=array(
		'res'=>$res,
		'num'=>$num
		);
		echo json_encode($data);
		
		
	}
	
	
	
	//首页搜索
	public function search() {
		$data = $_POST['search'];
		if($data!=''){
			echo json_encode(1);
			die;
		}
		$this->news = pc_base::load_model('new_model');
		$res = $this->news->select($where='title like %'.$cat.'%',$data ='*',$limit='20',$order="id desc");
		$num = count($res);
		$data=array(
		'res'=>$res,
		'num'=>$num
		);

		echo json_encode($data);
		/*$date= $_GET['ss'];
		$ums = 20;
		$ci = intval($_GET['ci']);
		$um = $ums+$ci;
		$getwhere = " a.title like '%".$date."%' order by a.id desc limit 0,".$um.'--';
		$getwhere = str_replace('\"', '', $getwhere);
		
		include template('content','search1');*/
	}	
	
	//内容页
	public function show() {
		$catid = intval($_GET['catid']);
		$id = intval($_GET['id']);

		if(!$catid || !$id) showmessage(L('information_does_not_exist'),'blank');
		$_userid = $this->_userid;
		$_username = $this->_username;
		$_groupid = $this->_groupid;

        $right_ad=query_one("select setting from dh_poster where spaceid=12");
        $right_ad=$right_ad['setting'];
        $right_ad=array_slice(explode("\n", $right_ad),3,2);
        foreach ($right_ad as $k => &$v) {
            $v['linkurl']=substr($v['linkurl'],24);
            $v=explode('=>',$v);
            $v=substr($v[1], 0,-1);
            $v=str_replace("'", '', $v);
            $v=substr($v,24);
        }

		$page = intval($_GET['page']);
		$page = max($page,1);
		$siteids = getcache('category_content','commons');
		$siteid = $siteids[$catid];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');
		
		if(!isset($CATEGORYS[$catid]) || $CATEGORYS[$catid]['type']!=0) showmessage(L('information_does_not_exist'),'blank');
		$this->category = $CAT = $CATEGORYS[$catid];
		$this->category_setting = $CAT['setting'] = string2array($this->category['setting']);
		$siteid = $GLOBALS['siteid'] = $CAT['siteid'];

		$MODEL = getcache('model','commons');
		$modelid = $CAT['modelid'];
		
		$tablename = $this->db->table_name = $this->db->db_tablepre.$MODEL[$modelid]['tablename'];
		$r = $this->db->get_one(array('id'=>$id));
		if(!$r || $r['status'] != 99) showmessage(L('info_does_not_exists'),'blank');

		$this->db->table_name = $tablename.'_data';
		$r2 = $this->db->get_one(array('id'=>$id));
		$rs = $r2 ? array_merge($r,$r2) : $r;

		//再次重新赋值，以数据库为准
		$catid = $CATEGORYS[$r['catid']]['catid'];
		$modelid = $CATEGORYS[$catid]['modelid'];

		require_once CACHE_MODEL_PATH.'content_output.class.php';
		$content_output = new content_output($modelid,$catid,$CATEGORYS);
		$data = $content_output->get($rs);
		extract($data);

		//检查文章会员组权限
		if($groupids_view && is_array($groupids_view)) {
			$_groupid = param::get_cookie('_groupid');
			$_groupid = intval($_groupid);
			if(!$_groupid) {
				$forward = urlencode(get_url());
				showmessage(L('login_website'),APP_PATH.'index.php?m=member&c=index&a=login&forward='.$forward);
			}
			if(!in_array($_groupid,$groupids_view)) showmessage(L('no_priv'));
		} else {
			//根据栏目访问权限判断权限
			$_priv_data = $this->_category_priv($catid);
			if($_priv_data=='-1') {
				$forward = urlencode(get_url());
				showmessage(L('login_website'),APP_PATH.'index.php?m=member&c=index&a=login&forward='.$forward);
			} elseif($_priv_data=='-2') {
				showmessage(L('no_priv'));
			}
		}
		if(module_exists('comment')) {
			$allow_comment = isset($allow_comment) ? $allow_comment : 1;
		} else {
			$allow_comment = 0;
		}
		//阅读收费 类型
		$paytype = $rs['paytype'];
		$readpoint = $rs['readpoint'];
		$allow_visitor = 1;

		if($readpoint || $this->category_setting['defaultchargepoint']) {
			if(!$readpoint) {
				$readpoint = $this->category_setting['defaultchargepoint'];
				$paytype = $this->category_setting['paytype'];
			}

			//检查是否支付过
			$allow_visitor = self::_check_payment($catid.'_'.$id,$paytype);
			if(!$allow_visitor) {
				$http_referer = urlencode(get_url());
				$allow_visitor = sys_auth($catid.'_'.$id.'|'.$readpoint.'|'.$paytype).'&http_referer='.$http_referer;
			} else {
				$allow_visitor = 1;
			}
		}

		//最顶级栏目ID
		$arrparentid = explode(',', $CAT['arrparentid']);
		$top_parentid = $arrparentid[1] ? $arrparentid[1] : $catid;

		$template = $template ? $template : $CAT['setting']['show_template'];
		if(!$template) $template = 'show';
		//SEO
		$seo_keywords = '';
		if(!empty($keywords)) $seo_keywords = implode(',',$keywords);
		$SEO = seo($siteid, $catid, $title, $description, $seo_keywords);

		define('STYLE',$CAT['setting']['template_list']);
		if(isset($rs['paginationtype'])) {
			$paginationtype = $rs['paginationtype'];
			$maxcharperpage = $rs['maxcharperpage'];
		}

		if($rs['paginationtype']!=0) {
			//手动分页
			$CONTENT_POS = strpos($content, '[page]');
			if($CONTENT_POS !== false) {
				$this->url = pc_base::load_app_class('url', 'content');
				$contents = array_filter(explode('[page]', $content));

				$pagenumber = count($contents);
				if (strpos($content, '[/page]')!==false && ($CONTENT_POS<7)) {
					$pagenumber--;
				}
				for($i=1; $i<=$pagenumber; $i++) {
					$pageurls[$i] = $this->url->show($id, $i, $catid, $rs['inputtime']);
				}
				$END_POS = strpos($content, '[/page]');
				if($END_POS !== false) {
					if($CONTENT_POS>7) {
						$content = '[page]'.$title.'[/page]'.$content;
						$content =str_replace("<img","<img onerror='nofind()'",$content);
					}
					if(preg_match_all("|\[page\](.*)\[/page\]|U", $content, $m, PREG_PATTERN_ORDER)) {
						foreach($m[1] as $k=>$v) {
							$p = $k+1;
							$titles[$p]['title'] = strip_tags($v);
							$titles[$p]['url'] = $pageurls[$p][0];
						}
					}
				}
				//当不存在 [/page]时，则使用下面分页
				$pages = content_pages($pagenumber,$page, $pageurls);
				//判断[page]出现的位置是否在第一位
				if($CONTENT_POS<7) {
					$content = $contents[$page];
					$content =str_replace("<img","<img onerror='nofind()'",$content);
				} else {
					if ($page==1 && !empty($titles)) {
						$content = $title.'[/page]'.$contents[$page-1];
						$content =str_replace("<img","<img onerror='nofind()'",$content);
					} else {
						$content = $contents[$page-1];
						$content =str_replace("<img","<img onerror='nofind()'",$content);

					}
				}
				if($titles) {
					list($title, $content) = explode('[/page]', $content);
					$content = trim($content);
					$content =str_replace("<img","<img onerror='nofind()'",$content);
					if(strpos($content,'</p>')===0) {
						$content = '<p>'.$content;
					}
					if(stripos($content,'<p>')===0) {
						$content = $content.'</p>';

					}
				}
			}
		}
		$this->db->table_name = $tablename;
		//上一页
		$previous_page = $this->db->get_one("`catid` = '$catid' AND `id`<'$id' AND `status`=99",'*','id DESC');
		//下一页
		$next_page = $this->db->get_one("`catid`= '$catid' AND `id`>'$id' AND `status`=99",'*','id ASC');

		if(empty($previous_page)) {
			$previous_page = array('title'=>L('first_page'), 'thumb'=>IMG_PATH.'nopic_small.gif', 'url'=>'javascript:alert(\''.L('first_page').'\');');
		}
		if(empty($next_page)) {
			$next_page = array('title'=>L('last_page'), 'thumb'=>IMG_PATH.'nopic_small.gif', 'url'=>'javascript:alert(\''.L('last_page').'\');');
		}
	$shoucang=$this->shoucang;

        /*<p class="xqt" style="width:1030px"><img class="imgxq" src="/uploadfile/images/<?php echo $c?>" style="display:block;margin:auto"></p>*/
        $str="";
        $temp_content=explode("><",$content);

        foreach($temp_content as $k=>$v){
            $str.='<p class="xqt" style="width:1030px"><img onerror="this.src=\'http://www.20152015.net/error.png\';this.style.display=\'none\';this.onerror=null;" class="imgxq" src="/uploadfile/images/'.$v.'" style="display:block;margin:auto"></p>';
        }
		include template('content',$template);
	}
	//列表页
	public function lists() {
		$catid = $_GET['catid'] = intval($_GET['catid']);
		$_priv_data = $this->_category_priv($catid);
		if($_priv_data=='-1') {
			$forward = urlencode(get_url());
			showmessage(L('login_website'),APP_PATH.'index.php?m=member&c=index&a=login&forward='.$forward);
		} elseif($_priv_data=='-2') {
			showmessage(L('no_priv'));
		}
		$_userid = $this->_userid;
		$_username = $this->_username;
		$_groupid = $this->_groupid;

		if(!$catid) showmessage(L('category_not_exists'),'blank');
		$siteids = getcache('category_content','commons');
		$siteid = $siteids[$catid];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');
		if(!isset($CATEGORYS[$catid])) showmessage(L('category_not_exists'),'blank');
		$CAT = $CATEGORYS[$catid];
		$siteid = $GLOBALS['siteid'] = $CAT['siteid'];
		extract($CAT);
		$setting = string2array($setting);
		//SEO
		if(!$setting['meta_title']) $setting['meta_title'] = $catname;
		$SEO = seo($siteid, '',$setting['meta_title'],$setting['meta_description'],$setting['meta_keywords']);
		define('STYLE',$setting['template_list']);
		$page = intval($_GET['page']);

		$template = $setting['category_template'] ? $setting['category_template'] : 'category';
		$template_list = $setting['list_template'] ? $setting['list_template'] : 'list';
		
		if($type==0) {
			$template = $child ? $template : $template_list;
			$arrparentid = explode(',', $arrparentid);
			$top_parentid = $arrparentid[1] ? $arrparentid[1] : $catid;
			$array_child = array();
			$self_array = explode(',', $arrchildid);
			//获取一级栏目ids
			foreach ($self_array as $arr) {
				if($arr!=$catid && $CATEGORYS[$arr][parentid]==$catid) {
					$array_child[] = $arr;
				}
			}
			$arrchildid = implode(',', $array_child);
			//URL规则
			$urlrules = getcache('urlrules','commons');
			$urlrules = str_replace('|', '~',$urlrules[$category_ruleid]);
			$tmp_urls = explode('~',$urlrules);
			$tmp_urls = isset($tmp_urls[1]) ?  $tmp_urls[1] : $tmp_urls[0];
			preg_match_all('/{\$([a-z0-9_]+)}/i',$tmp_urls,$_urls);
			if(!empty($_urls[1])) {
				foreach($_urls[1] as $_v) {
					$GLOBALS['URL_ARRAY'][$_v] = $_GET[$_v];
				}
			}
			define('URLRULE', $urlrules);
			$GLOBALS['URL_ARRAY']['categorydir'] = $categorydir;
			$GLOBALS['URL_ARRAY']['catdir'] = $catdir;
			$GLOBALS['URL_ARRAY']['catid'] = $catid;
			$ums = 20;
			$ci = intval($_GET['ci']);
			$um = $ums+$ci;
			include template('content',$template);
		} else {
		//单网页
			$this->page_db = pc_base::load_model('page_model');
			$r = $this->page_db->get_one(array('catid'=>$catid));
			if($r) extract($r);
			$template = $setting['page_template'] ? $setting['page_template'] : 'page';
			$arrchild_arr = $CATEGORYS[$parentid]['arrchildid'];
			if($arrchild_arr=='') $arrchild_arr = $CATEGORYS[$catid]['arrchildid'];
			$arrchild_arr = explode(',',$arrchild_arr);
			array_shift($arrchild_arr);
			$keywords = $keywords ? $keywords : $setting['meta_keywords'];
			$SEO = seo($siteid, 0, $title,$setting['meta_description'],$keywords);
			include template('content',$template); 
		}
	}
	
	//JSON 输出
	public function json_list() {
		if($_GET['type']=='keyword' && $_GET['modelid'] && $_GET['keywords']) {
		//根据关键字搜索
			$modelid = intval($_GET['modelid']);
			$id = intval($_GET['id']);

			$MODEL = getcache('model','commons');
			if(isset($MODEL[$modelid])) {
				$keywords = safe_replace(new_html_special_chars($_GET['keywords']));
				$keywords = addslashes(iconv('utf-8','gbk',$keywords));
				$this->db->set_model($modelid);
				$result = $this->db->select("keywords LIKE '%$keywords%'",'id,title,url',10);
				if(!empty($result)) {
					$data = array();
					foreach($result as $rs) {
						if($rs['id']==$id) continue;
						if(CHARSET=='gbk') {
							foreach($rs as $key=>$r) {
								$rs[$key] = iconv('gbk','utf-8',$r);
							}
						}
						$data[] = $rs;
					}
					if(count($data)==0) exit('0');
					echo json_encode($data);
				} else {
					//没有数据
					exit('0');
				}
			}
		}

	}
	
	
	/**
	 * 检查支付状态
	 */
	protected function _check_payment($flag,$paytype) {
		$_userid = $this->_userid;
		$_username = $this->_username;
		if(!$_userid) return false;
		pc_base::load_app_class('spend','pay',0);
		$setting = $this->category_setting;
		$repeatchargedays = intval($setting['repeatchargedays']);
		if($repeatchargedays) {
			$fromtime = SYS_TIME - 86400 * $repeatchargedays;
			$r = spend::spend_time($_userid,$fromtime,$flag);
			if($r['id']) return true;
		}
		return false;
	}
	
	/**
	 * 检查阅读权限
	 *
	 */
	protected function _category_priv($catid) {
		$catid = intval($catid);
		if(!$catid) return '-2';
		$_groupid = $this->_groupid;
		$_groupid = intval($_groupid);
		if($_groupid==0) $_groupid = 8;
		$this->category_priv_db = pc_base::load_model('category_priv_model');
		$result = $this->category_priv_db->select(array('catid'=>$catid,'is_admin'=>0,'action'=>'visit'));
		if($result) {
			if(!$_groupid) return '-1';
			foreach($result as $r) {
				if($r['roleid'] == $_groupid) return '1';
			}
			return '-2';
		} else {
			return '1';
		}
	 }
	 public function pv(){
		 $ip=$this->getIP();
         $uri=$_REQUEST['href'];
		 //$ip="114.91.81.188";
		 $url="http://ip2l.com/?ips=".$ip."&locate_ip=Locate!";
		 $content=file_get_contents($url);
		 $pattern = '/&nbsp;<\/div><\/td><td align="left" valign="top" class="t">(.+?)<\/td><\/tr><\/table>/is';
		 preg_match($pattern, $content, $match);
		//$match[0] 即为<div class="nav" monkey="nav">和<div class="head-ad">之间的所有源码
		 $content=$match[0];
		 //echo $content;
		 $array=explode('&nbsp;</div></td><td align="left" valign="top" class="t">',$content);
		 $array=$array['2'];
		 $array=str_replace('&nbsp;</td><td align="left" valign="top" class="t">','|',$array);
		 $array=str_replace('</td></tr></table>','',$array);
		 $array=addslashes($array);
		 $array=explode('|',$array);
		 $country=$array[0];
		 $province=$array[1];
		 $city=$array[2];
		 $user_id=$this->_userid?$this->_userid:0;
		 $ctime=date('Y-m-d H:i:s',time());
		 session_start();
		 $cookie_id=session_id();
		 $pv_model = pc_base::load_model('pv_model');
		 $data=array(
			'ip'=>$ip,
			'user_id'=>$user_id,
			'ctime'=>$ctime,
			'cookie'=>$cookie_id,
			'country'=>isset($country)?$country:'',
			'province'=>isset($province)?$province:'',
			'city'=>isset($city)?$city:'',
			'address'=>isset($address)?$address:'',
            'page'=>$uri
		 );
		 $isok=$pv_model->insert($data);
         p($isok);
	 }
	 public function getIP() { 
		if (getenv('HTTP_CLIENT_IP')) { 
			$ip = getenv('HTTP_CLIENT_IP'); 
		} 
		elseif (getenv('HTTP_X_FORWARDED_FOR')) { 
			$ip = getenv('HTTP_X_FORWARDED_FOR'); 
		} 
		elseif (getenv('HTTP_X_FORWARDED')) { 
			$ip = getenv('HTTP_X_FORWARDED'); 
		} 
		elseif (getenv('HTTP_FORWARDED_FOR')) { 
			$ip = getenv('HTTP_FORWARDED_FOR'); 
		} 
		elseif (getenv('HTTP_FORWARDED')) { 
			$ip = getenv('HTTP_FORWARDED'); 
		} 
		else { 
			$ip = $_SERVER['REMOTE_ADDR']; 
		} 
		return $ip; 
	} 
}
?>